<?php

namespace app\controllers\api;

use app\models\News;
use app\models\User;
use Yii;
use yii\base\Exception;
use yii\base\UserException;
use yii\web\NotFoundHttpException;

class NewsController extends BaseController {
    public function actionCreate() {
        $user = $this->check([User::ROLE_GOV, User::ROLE_ADMIN, ]);
        $this->checkModify();
        $post = Yii::$app->request->post();
        $model = new News();
        $model->loadBeforeFilter($post, ['type', 'title', 'content', /*'time', */'country_id', 'role', ]);
        if(!$model->title) {
            throw new UserException('标题未填写');
        }
        $model->author_id = $user->id;
        $model->time = date('Y-m-d H:i:s');
        if($user->role == User::ROLE_GOV) {
            $model->country_id = $user->country_id;
        }
        $model->save();
        $this->log('新闻 - 创建', $model->id);
        return $this->renderSuccess([]);
    }

    public function actionGet($id) {
        $user = $this->check();
        $model = News::findOne($id);
        if(!$model) {
            throw new UserException('新闻/公告不存在');
        }
        if(!empty($model->country_id) && $model->country_id != $user->country_id ||
            !empty($model->role) && $model->role != $user->role) {
            $model->country_id = $user->country_id;
        }
        $this->log('新闻 - 查询', $model->id);
        return $this->renderSuccess([
            'news' => $model,
        ]);
    }

    public function actionList($type = null) {
        $user = $this->check();
        $models = News::find()
            ->andWhere(['or', ['country_id'=>$user->country_id], ['country_id'=>null]])
            ->andWhere(['or', ['role'=>$user->role], ['role'=>null]])
            ->orWhere(['author_id'=>$user->id])
            ->andFilterWhere([
                'type' => $type,
            ])
            ->all();
        $this->log('新闻 - 查询列表', '');
        return $this->renderSuccess([
            'newsList' => $models,
        ]);
    }
}
